////////////////////////////////////////////////////////////////////////////////
//                                                                            //
// The MIT License (MIT)                                                      //
//                                                                            //
// Copyright (c) 2013 Charles Teague                                          //
//                                                                            //
// Permission is hereby granted, free of charge, to any person obtaining a    //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation  //
// the rights to use, copy, modify, merge, publish, distribute, sublicense,   //
// and/or sell copies of the Software, and to permit persons to whom the      //
// Software is furnished to do so, subject to the following conditions:       //
//                                                                            //
// The above copyright notice and this permission notice shall be included in //
// all copies or substantial portions of the Software.                        //
//                                                                            //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,   //
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL    //
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING    //
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER        //
// DEALINGS IN THE SOFTWARE.                                                  //
//                                                                            //
////////////////////////////////////////////////////////////////////////////////
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

using RPSDAL;
using RPSDAL.EntityClasses;
using RPSDAL.CollectionClasses;
using RPSDAL.HelperClasses;
using RPSDAL.FactoryClasses;

using SD.LLBLGen.Pro.ORMSupportClasses;


public partial class ContactTypeList : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) 
        {
            if (Parameters.LoggedUser != -1)
            {
                UserEntity eUser = new UserEntity(Parameters.LoggedUser);
                RoleEntity eRole = new RoleEntity(eUser.RoleId);

                if (!eRole.HasEditContactType)
                {
                    Parameters.LoggedUser = -1;
                    Response.Redirect("Default.aspx");
                    return;
                }
            }
            
            grdContactTypes.PageSize = Parameters.PageSize;
            LoadContactTypeList();

        }

    }



    #region methods

    private void LoadContactTypeList()
    {
        ContactTypeCollection cContactTypes = new ContactTypeCollection();
        cContactTypes.GetMulti(null);

        grdContactTypes.DataSource = cContactTypes;
        grdContactTypes.DataBind();

    }

    /// <summary>
    /// insert a new contact type or 
    /// update an existing contact type
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Save(object sender, EventArgs e)
    {
        Response.Redirect("ContactType.aspx");

        #region old

        /*ContactTypeCollection cContactTypes = new ContactTypeCollection();
        cContactTypes.GetMulti(null);

        if (Request.QueryString["Id"] == null)
        {
            // insert new contact type
            Global.UserLogSave(Parameters.LoggedUser, "Add New Contact Type");
            ContactTypeEntity eContactType = new ContactTypeEntity();
            eContactType.Name = txtContactType.Text;

            int index;
            bool bExist = false;
            for (index = 0; index < cContactTypes.Count; index++)
            {
                if (cContactTypes[index].Name == txtContactType.Text)
                {
                    bExist = true;
                    break;
                }
            }
            if (!bExist)
            {
                lblSteluta.Visible = false;
                lblTypeExist.Visible = false;
                eContactType.Save();
                Response.Redirect("ContactTypeList.aspx");
            }
            else
            {
                lblSteluta.Visible = true;
                lblTypeExist.Visible = true;
            }           
        }
        else 
        {
            // update existing contact type
            Global.UserLogSave(Parameters.LoggedUser, "Update New Contact Type");
            ContactTypeEntity eContactType = new ContactTypeEntity(Convert.ToInt32(Global.DecryptString(Request.QueryString["Id"].ToString())));
            eContactType.Name = txtContactType.Text;

            int index;
            bool bExist = false;
            for (index = 0; index < cContactTypes.Count; index++)
            {
                if (cContactTypes[index].Name == txtContactType.Text)
                {
                    bExist = true;
                    break;
                }
            }
            if (!bExist)
            {
                lblSteluta.Visible = false;
                lblTypeExist.Visible = false;
                eContactType.Save();
                Response.Redirect("ContactTypeList.aspx");
            }
            else
            {
                lblSteluta.Visible = true;
                lblTypeExist.Visible = true;
            }        
          
        }*/

        #endregion old

    }

    #endregion methods


    protected void Command(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Page")
        {
            return;
        }
        if (((System.Web.UI.WebControls.Button)(e.CommandSource)).Text == "Edit")
        {
            // edit contact type
            try
            {
                Global.UserLogSave(Parameters.LoggedUser, "Edit Contact Type id="+e.CommandArgument.ToString());
                Response.Redirect("ContactType.aspx?id=" + Global.EncryptString(e.CommandArgument.ToString()));
            }
            catch { }
        }
        else 
        {
            // delete contact type            
            try
            {
                Global.UserLogSave(Parameters.LoggedUser, "Delete Contact Type id="+e.CommandArgument.ToString());
                int contactTypeId = Convert.ToInt32(e.CommandArgument);

                // delete all contacts of this type
                ContactCollection cContacts = new ContactCollection();
                IPredicateExpression filterContacts = new PredicateExpression();
                filterContacts.Add(ContactFields.ContactTypeId == contactTypeId);
                cContacts.GetMulti(filterContacts);

                for (int i = 0; i < cContacts.Count; i++) 
                {
                    RemoveContact(cContacts[i].ContactId);
                }
                
                ContactTypeEntity eContactEntity = new ContactTypeEntity(contactTypeId);
                eContactEntity.Delete();
                Response.Redirect("ContactTypeList.aspx");
            }
            catch { }
        }
    }

    private void RemoveContact(int contactId) 
    {
        ContactEntity eContact = new ContactEntity(contactId);
        ContactFileCollection cContactFiles = new ContactFileCollection();
        IPredicateExpression filter = new PredicateExpression();
        filter.Add(ContactFileFields.ContactId == eContact.ContactId);
        cContactFiles.GetMulti(filter);

        // delete contact files
        for (int i = 0; i < cContactFiles.Count; i++)
        {
            if (File.Exists(cContactFiles[i].ServerFile))
            {
                File.Delete(cContactFiles[i].ServerFile);
            }
        }

        cContactFiles.DeleteMulti(filter);


        CallCollection cCalls = new CallCollection();
        filter = new PredicateExpression();
        filter.Add(CallFields.ContactId == eContact.ContactId);
        cCalls.DeleteMulti(filter);



        ContactGroupMemberCollection cContactGroupMembers = new ContactGroupMemberCollection();
        filter = new PredicateExpression();
        filter.Add(ContactGroupMemberFields.ContactId == eContact.ContactId);
        cContactGroupMembers.DeleteMulti(filter);

        eContact.Delete();
    }

    protected void RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Button button = (Button)e.Row.FindControl("btnDelete");
            button.Attributes.Add("onclick", @"javascript:return confirm('Are you sure you want to delete this contact type? This will delete all contacts of this type.');");
        }
    }

    protected void grdContactTypes_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdContactTypes.PageIndex = e.NewPageIndex;
        LoadContactTypeList();
    }
}
